package com.xielx.ohs.web;


import java.io.IOException;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletResponse;

import com.xielx.ohs.bean.OhsParam;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController extends BaseController {
        private static final Logger log = LoggerFactory.getLogger(MainController.class);
        private static final CloseableHttpClient httpClient = HttpClients.createDefault();
        private static final String GET = "GET";

        @RequestMapping({"/proxy"})
        public void proxy(@RequestBody OhsParam param, HttpServletResponse response) throws IOException {
                try {
                        log.info("visit web:{}", param.getUrl());
                        HttpRequestBase reqeust = createRequest(param);
                        CloseableHttpResponse result = httpClient.execute(reqeust);
                        response.setStatus(result.getStatusLine().getStatusCode());
                        for (Header header : result.getAllHeaders()) {
                                response.setHeader(header.getName(), header.getValue());
                        }
                        byte[] bs = EntityUtils.toByteArray(result.getEntity());
                        response.getOutputStream().write(bs);
                } catch (Exception e) {
                        log.info("visit web error:", e);
                }
        }

        private HttpRequestBase createRequest(OhsParam param) {
                HttpRequestBase requestBase = "GET".equalsIgnoreCase(param.getMethod()) ? new HttpGet(param.getFullUrl()) : new HttpPost(param.getFullUrl());
                requestBase.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
                if (null == param.getHeader()) {
                        return requestBase;
                }
                for (Entry<String, String> entry : param.getHeader().entrySet()) {
                        requestBase.setHeader((String) entry.getKey(), (String) entry.getValue());
                }
                return requestBase;
        }
}
